layui.define(function (exports) {
    "use strict";

    // 匹配
    const betweens = function (reg, str) {
        const res = str.match(reg, str)
        if (res && res[1] !== undefined) {
            return res[1]
        } else {
            return false
        }
    }
    // as 前后
    const betweenAs = function (str) {
        let index = str.indexOf('as');
        if (index === -1) {
            return false;
        }
        let before = str.slice(0, index).trim();
        let after = str.slice(index + 2).trim();
        return [before, after]
    }
    // 数据转义
    const escape = function (str) {
        if (typeof str === "string") {
            const div = document.createElement('div');
            div.appendChild(document.createTextNode(str));
            return div.innerHTML;
        } else {
            return str
        }
    }
    const isVar = function (str) {
        return (str.replace(/{([^}]+)}/g, '${escape($1)}'));
    }
    const jmTpl = function (template, data) {
        // 模板必须为 string 类型
        if (typeof template !== 'string') {
            console.log("参数1 'template' 必须是字符串。")
        }
        template = template
            .replace(/\{\s*\n*\s*/g, "{")
            .replace(/\s*\n*\s*\}/g, "}")
            .replace(/lt;/g, "<")
            .replace(/gt;/g, ">")
        // 字符串替换
        template = template.replaceAll("{/if}", "}")
            .replaceAll("{:else}", "}else{")
            .replaceAll("{/each}", "});")
            .replaceAll("{/for}", "}")

        const arrays = template.split("\n")
        let strParts = [`let kbView = '';
        const keys = Object.keys(kbData);
        for (const key of keys) {
        window[key] = kbData[key];}`]
        for (const item of arrays) {
            const i = item.trim()

            const i_if = betweens(/{#if\s+(.*?)}/, i)
            const i_elseif = betweens(/{:else\s*\n*\s*if\s+(.*?)}/, i)
            const i_for = betweens(/{#for\s+(.*?)}/, i)
            const i_each = betweens(/{#each\s+(.*?)}/, i)
            const i_html = betweens(/{@html\s+(.*?)}/, i)
            const i_data = betweens(/.*?{(.*?)}.*?/, i)

            if (i === "") {
                // 跳过
                continue
            } else if (["}", "}else{", "});"].includes(i)) {
                strParts.push(`${i}`)
            } else if (i_if) {
                strParts.push(`if(${i_if}){`)
            } else if (i_elseif) {
                strParts.push(`}else if(${i_elseif}){`)
            } else if (i_for) {
                strParts.push(`for(${i_for}){`)
            } else if (i_each) {
                const arr = betweenAs(i_each)
                strParts.push(`${arr[0]}.forEach(function(${arr[1]}){`)
            } else if (i_html) {
                strParts.push(`kbView += ${i_html};`)
            } else if (i_data) {
                strParts.push(`kbView += \`${isVar(i)}\`;`)
            } else {
                strParts.push(`kbView += \`${i}\`;`)
            }
        }
        strParts.push("return kbView;")
        const newStr = strParts.join('\n');
        try {
            const fn = new Function('kbData,escape', newStr);
            const result = fn(data, escape);
            return typeof result !== "undefined" ? result : "";
        } catch (e) {
            console.error(`模板报错：${e}`)
            return template;
        }
    }

    exports('jmTpl', jmTpl); // 输出模块
});  